<?php
// +----------------------------------------------------------------------
// | KITEGO-Admin「开箱即用」「人人全栈」
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2024 https://www.kitego.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed KITEGO并不是自由软件，未经许可不能去掉KITEGO相关版权
// +----------------------------------------------------------------------
// | Author: KITEGO Team <bd@kitego.cn>
// +----------------------------------------------------------------------

namespace app\adminapi\middleware;

use Closure;
use Exception;
use kitego\traits\AdminAuthTrait;
use think\Request;

class AdminAuthMiddleware
{
    use AdminAuthTrait;

    /**
     * 权限中间件
     * @throws Exception
     */
    public function handle(Request $request, Closure $next)
    {
        // 无需鉴权的接口放行
        if ($request->invokeController->checkSafeAction()) {
            return $next($request);
        }

        // 已登录且是超管，直接放行
        if (isset(request()->userId) && (request()->userId == 1 || in_array('super', $request->adminRoleAlias))) {
            return $next($request);
        }

        // 当前接口和接口类型
        $rule = trim($request->pathinfo());
        $method = trim(strtolower($request->method()));

        // 获取所有接口
        list($allAuthListQuery) = self::getAdminAuthList();

        // 已登录请求
        $allMethodWithAuth = [];
        foreach ($allAuthListQuery as $va) {
            if (!in_array($va['id'], $request->adminRoleMenuIds)) {
                continue;
            }
            $allMethodWithAuth[trim(strtolower($va['method']))][] = $va['auth'];
        }

        if (!isset($allMethodWithAuth[$method]) || !in_array($rule, $allMethodWithAuth[$method])) {
            exception('未授权访问');
        }

        return $next($request);
    }
}
